package com.xsy.middleware.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xsy.middleware.entity.FileRecord;
import com.xsy.middleware.mapper.DbOptMapper;
import com.xsy.middleware.mapper.FileRecordMapper;
import com.xsy.middleware.utils.CrmApiUtils;
import com.xsy.middleware.utils.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;

/**
 * @Description: 操作配置表、配置表明细
 * @Author: 黎炎松
 * @Date: 2024/4/22 10:20
 */
@Slf4j
@Service
public class DataBackService {

    @Autowired
    private CrmApiUtils crmApiUtils;

    @Autowired
    private DbOptMapper dbOptMapper;

    @Autowired
    private FileRecordMapper fileRecordMapper;

    /**
     * 执行sql
     * @param sql
     */
    public void executeSql(String sql) {
        dbOptMapper.executeSql(sql);
    }

    /**
     * 判断表是否存在
     * @param tableName
     * @return
     */
    public Boolean isTableExist(String tableName) {
        int count = dbOptMapper.isTableExist(tableName);
        return count > 0;
    }

    /**
     * 查询数据id
     * @param sql
     * @return
     */
    public List<HashMap<String, Object>> selectTableData(String sql) {
        return dbOptMapper.selectTableData(sql);
    }

    /**
     * 查询数据
     * @param sql
     * @return
     */
    public List<Long> selectTableIds(String sql) {
        return dbOptMapper.selectTableIds(sql);
    }

    /**
     * 批量插入
     * @param fileRecordList
     * @return
     */
    public int batchInsertFileRecord(List<FileRecord> fileRecordList) {
        return fileRecordMapper.batchInsertFileRecord(fileRecordList);
    }

    /**
     * 查询文件列表格局模块、模块id
     * @param tableName
     * @param moduleIdList
     * @return
     */
    public List<String> queryFileUrlByModule (String tableName, List<Long> moduleIdList) {
        return fileRecordMapper.queryFileUrlByModule(tableName, moduleIdList);
    }

    public int delFileRecordByModule (String tableName, List<Long> moduleIdList) {
        return fileRecordMapper.delFileRecordByModule(tableName, moduleIdList);
    }

    /**
     * 修改配置表
     * @param jsonObject
     * @return
     * @throws UnsupportedEncodingException
     */
    public ResultVo updateDataBackup (JSONObject jsonObject) throws UnsupportedEncodingException {
        return crmApiUtils.update("dataBackup__c", jsonObject);
    }

    /**
     * 获取配置表信息
     * @param tableName
     * @return
     */
    public JSONObject getDataBackup(String tableName) throws UnsupportedEncodingException {
        // 查询配置表信息
        String sql = "select id,name,entityType,objectName__c,objectApiKey__c,lastSyncTime__c,lastSyncFileTime__c,isCreateTable__c " +
                "from dataBackup__c where objectApiKey__c  = '" + tableName +"'";
        JSONObject tableData = crmApiUtils.queryOne(sql);
        log.info("配置表数据 : {}", tableData);
        return tableData;
    }

    /**
     * 获取已经建表的配置表信息
     * @param isCreate 1: 已建表  2: 未建表
     * @return
     * @throws UnsupportedEncodingException
     */
    public JSONArray getDataBackupByCreate(int isCreate) throws UnsupportedEncodingException {
        // 查询配置表信息
        String sql = "select id,name,entityType,objectName__c,objectApiKey__c,lastSyncTime__c,lastSyncFileTime__c,isCreateTable__c " +
                "from dataBackup__c where isCreateTable__c = " + isCreate + " order by createdAt desc";
        JSONArray dataBackList = crmApiUtils.query(sql);
        log.info("配置表数量 : {}", dataBackList.size());
        return dataBackList;
    }

    /**
     * 根据类型获取配置表需要同步明细
     * @param dataBackupId
     * @param queryType 1: 配置表所有字段  2: 配置表需要同步的字段  3：配置表需要同步且是文件同步字段
     * @return
     * @throws UnsupportedEncodingException
     */
    public JSONArray getDataBackupDetailByType(Long dataBackupId, int queryType) throws UnsupportedEncodingException {
        String sql = "select id,name,fieldName__c,fieldApiKey__c,fieldType__c,dbFieldType__c from dataBackupDetail__c ";
        switch (queryType)  {
            case 1:
                // 1: 配置表所有字段 - 创建表格使用
                sql += " where dataBackup__c = " + dataBackupId;
                break;
            case 2:
                // 2: 配置表需要同步的字段 - 初始化数据使用
                // 用户表同步查询报错的字段: passwordRuleId isVirtual relatedDepart relatedProduct relatedArea relatedBusiness relatedIndustry (在crm表中设置不需同步
                sql += " where (isSync__c = 1 or isSync__c is null) and dataBackup__c = " + dataBackupId;
                break;
            case 3:
                // 3：配置表需要同步且是文件同步字段 - 同步文件使用
                sql += " where (isSync__c = 1 or isSync__c is null) and isFile__c = 1 and dataBackup__c = " + dataBackupId;
                break;
        }
        JSONArray tableFileList = crmApiUtils.query(sql);
        log.info("配置表明细数据数量 : {}", tableFileList.size());
        return tableFileList;
    }


    /**
     * 获取crm表格数据
     * @param sql
     * @return
     */
    public JSONArray getCrmTableData(String sql) {
        log.info("getCrmTableData : {}", sql);
        return crmApiUtils.getTableData(sql);
    }

}
